<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h3>个人信息</h3>
          <el-button type="primary" @click="handleEdit">编辑资料</el-button>
        </div>
      </template>

      <div class="profile-content">
        <div class="avatar-section">
          <el-avatar :size="100" :src="nurseInfo.avatar" />
          <div class="status-switch">
            <span>接单状态：</span>
            <el-switch
              v-model="nurseInfo.isOnline"
              active-text="在线"
              inactive-text="离线"
              @change="handleStatusChange"
            />
          </div>
        </div>

        <div class="info-section">
          <div class="info-row">
            <span class="label">工号：</span>
            <span>{{ nurseInfo.nurseId }}</span>
          </div>
          <div class="info-row">
            <span class="label">姓名：</span>
            <span>{{ nurseInfo.name }}</span>
          </div>
          <div class="info-row">
            <span class="label">性别：</span>
            <span>{{ nurseInfo.gender }}</span>
          </div>
          <div class="info-row">
            <span class="label">年龄：</span>
            <span>{{ nurseInfo.age }}岁</span>
          </div>
          <div class="info-row">
            <span class="label">联系电话：</span>
            <span>{{ nurseInfo.phone }}</span>
          </div>
          <div class="info-row">
            <span class="label">服务区域：</span>
            <span>{{ nurseInfo.serviceArea }}</span>
          </div>
          <div class="info-row">
            <span class="label">从业年限：</span>
            <span>{{ nurseInfo.experience }}年</span>
          </div>
          <div class="info-row">
            <span class="label">个人简介：</span>
            <span class="description">{{ nurseInfo.description }}</span>
          </div>
          <div class="info-row">
            <span class="label">服务价格：</span>
            <span>{{ nurseInfo.money }}元</span>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="certificate-card">
      <template #header>
        <div class="card-header">
          <h3>资质证书</h3>
          <el-button type="primary" @click="handleAddCertificate">添加证书</el-button>
        </div>
      </template>

      <div class="certificate-list">
        <el-table :data="certificates" stripe style="width: 100%">
          <el-table-column prop="name" label="证书名称" />
          <el-table-column prop="number" label="证书编号" />
          <el-table-column prop="issueDate" label="发证日期" />
          <el-table-column prop="validUntil" label="有效期至" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'valid' ? 'success' : 'danger'">
                {{ scope.row.status === 'valid' ? '有效' : '已过期' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="证书图片" width="100">
            <template #default="scope">
              <el-image
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
                class="certificate-image"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button 
                type="primary" 
                link
                @click="handleUpdateCertificate(scope.row)"
              >
                更新
              </el-button>
              <el-button 
                type="danger" 
                link
                @click="handleDeleteCertificate(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="500px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="服务价格" prop="money">
          <el-input v-model="editForm.money" />
        </el-form-item>
        <el-form-item label="工号" prop="jobnumber">
          <el-input v-model="editForm.jobnumber" />
        </el-form-item>
        <el-form-item label="服务区域" prop="serviceArea">
          <el-select v-model="editForm.serviceArea" multiple placeholder="选择服务区域">
            <el-option
              v-for="item in areaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="从业年限" prop="experience">
          <el-input-number v-model="editForm.experience" :min="0" :max="50" />
        </el-form-item>
        <el-form-item label="个人简介" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/更新证书对话框 -->
    <el-dialog
      v-model="certificateDialogVisible"
      :title="isEditingCertificate ? '更新证书' : '添加证书'"
      width="500px"
    >
      <el-form :model="certificateForm" :rules="certificateRules" ref="certificateFormRef" label-width="100px">
        <el-form-item label="证书名称" prop="name">
          <el-input v-model="certificateForm.name" />
        </el-form-item>
        <el-form-item label="证书编号" prop="number">
          <el-input v-model="certificateForm.number" />
        </el-form-item>
        <el-form-item label="发证日期" prop="issueDate">
          <el-date-picker
            v-model="certificateForm.issueDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="有效期至" prop="validUntil">
          <el-date-picker
            v-model="certificateForm.validUntil"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="证书图片" prop="image">
          <el-upload
            class="certificate-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleCertificateImageSuccess"
          >
            <img v-if="certificateForm.image" :src="certificateForm.image" class="certificate" />
            <el-icon v-else class="certificate-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="certificateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCertificate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {ip} from '@/router/ip.js'

// 护士信息
const nurseInfo = ref({
  nurseId: '',
  name: '',
  gender: '',
  age: 0,
  phone: '',
  avatar: '',
  serviceArea: '',
  experience: 0,
  description: '',
  isOnline: false,
  money: 0 // 新增金额字段
})

// 证书列表
const certificates = ref([
  {
    id: 1,
    name: '护士执业证书',
    number: 'RN202401010001',
    issueDate: '2020-01-01',
    validUntil: '2025-12-31',
    status: 'valid',
    image: 'https://example.com/cert1.jpg'
  }
])

// 编辑表单相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  avatar: '',
  name: '',
  phone: '',
  serviceArea: [],
  experience: 0,
  description: '',
  money: 0,// 新增字段
  jobnumber: '' // 新增工号字段
})

// 证书表单相关
const certificateDialogVisible = ref(false)
const certificateFormRef = ref(null)
const isEditingCertificate = ref(false)
const certificateForm = reactive({
  name: '',
  number: '',
  issueDate: '',
  validUntil: '',
  image: ''
})

// 区域选项
const areaOptions = [
  { label: '海淀区', value: 'haidian' },
  { label: '朝阳区', value: 'chaoyang' },
  { label: '西城区', value: 'xicheng' }
]

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  serviceArea: [
    { required: true, message: '请选择服务区域', trigger: 'change' }
  ],
  experience: [
    { required: true, message: '请输入从业年限', trigger: 'blur' }
  ]
}

const certificateRules = {
  name: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
  number: [{ required: true, message: '请输入证书编号', trigger: 'blur' }],
  issueDate: [{ required: true, message: '请选择发证日期', trigger: 'change' }],
  validUntil: [{ required: true, message: '请选择有效期', trigger: 'change' }]
}

// 处理在线状态变更
const handleStatusChange = async (value) => {
  try {
    // TODO: 调用更新状态API
    ElMessage.success(value ? '已切换为在线状态' : '已切换为离线状态')
  } catch (error) {
    nurseInfo.value.isOnline = !value
    ElMessage.error('状态切换失败')
  }
}

// 编辑个人信息
const handleEdit = () => {
  Object.assign(editForm, {
    avatar: nurseInfo.value.avatar,
    name: nurseInfo.value.name,
    phone: nurseInfo.value.phone,
    serviceArea: [nurseInfo.value.serviceArea],
    experience: nurseInfo.value.experience,
    description: nurseInfo.value.description,
    money: nurseInfo.value.money, // 初始化金钱字段的值
    jobnumber: nurseInfo.value.nurseId // 初始化工号字段的值
  })
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return;

    await editFormRef.value.validate();

    const requestData = {
      caregiverid: localStorage.getItem('caregiverId'),
      name: editForm.name,
      phone: editForm.phone,
      address: editForm.serviceArea.join(','),
      serviceyears: editForm.experience,
      biography: editForm.description,
      avater: editForm.avatar,
      money: editForm.money,
      jobnumber: editForm.jobnumber // 新增工号字段
    };
    console.log('请求数据:', requestData);

    const response = await fetch(`http://${ip}:8000/api/updateCaregiver`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    });

    console.log('响应状态:', response.status);
    if (!response.ok) {
      throw new Error('更新信息失败');
    }

    // 更新本地数据
    Object.assign(nurseInfo.value, {
      avatar: editForm.avatar,
      name: editForm.name,
      phone: editForm.phone,
      serviceArea: editForm.serviceArea.join(','),
      experience: editForm.experience,
      description: editForm.description,
      money: editForm.money,
      nurseId: editForm.jobnumber // 更新本地工号显示
    });

    ElMessage.success('个人信息更新成功');
    editDialogVisible.value = false;
};
// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  editForm.avatar = response.url
}

// 证书相关方法
const handleAddCertificate = () => {
  isEditingCertificate.value = false
  Object.assign(certificateForm, {
    name: '',
    number: '',
    issueDate: '',
    validUntil: '',
    image: ''
  })
  certificateDialogVisible.value = true
}

const handleUpdateCertificate = (cert) => {
  isEditingCertificate.value = true
  Object.assign(certificateForm, cert)
  certificateDialogVisible.value = true
}

const handleDeleteCertificate = async (cert) => {
  try {
    await ElMessageBox.confirm(
      '确认删除该证书？',
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用删除证书API
    certificates.value = certificates.value.filter(item => item.id !== cert.id)
    ElMessage.success('证书已删除')
  } catch {}
}

const handleCertificateImageSuccess = (response) => {
  certificateForm.image = response.url
}

const submitCertificate = async () => {
  if (!certificateFormRef.value) return
  
  try {
    await certificateFormRef.value.validate()
    // TODO: 调用添加/更新证书API
    
    if (isEditingCertificate.value) {
      const index = certificates.value.findIndex(item => item.id === certificateForm.id)
      if (index !== -1) {
        certificates.value[index] = { ...certificateForm }
      }
      ElMessage.success('证书更新成功')
    } else {
      certificates.value.push({
        id: Date.now(),
        ...certificateForm,
        status: 'valid'
      })
      ElMessage.success('证书添加成功')
    }
    
    certificateDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 在 setup 函数中添加获取陪护师信息的方法
const fetchNurseInfo = async () => {
    const caregiverId = localStorage.getItem('caregiverId')
    if (!caregiverId) {
      ElMessage.error('未找到陪护师ID，请重新登录或联系管理员')
      throw new Error('未找到陪护师ID')
    }

    const response = await fetch(`http://${ip}:8000/api/getCaregiverById?caregiverid=${caregiverId}`)
    if (!response.ok) {
      throw new Error('获取陪护师信息失败')
    }
    const data = await response.json()

    nurseInfo.value = {
      nurseId: data.jobnumber,
      name: data.name,
      gender: data.gender,
      age: data.age,
      phone: data.phone,
      avatar: data.avater,
      serviceArea: data.address,
      experience: data.serviceyears,
      description: data.biography,
      isOnline: data.status === 'online',
      money: data.money // 新增金额字段
    }
}

onMounted(() => {
  fetchNurseInfo()
  // TODO: 获取证书列表
})
</script>

<style scoped lang="scss">
.profile-container {
  .profile-card {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
    }
  }

  .profile-content {
    display: flex;
    gap: 40px;

    .avatar-section {
      text-align: center;

      .status-switch {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
      }
    }

    .info-section {
      flex: 1;

      .info-row {
        margin-bottom: 15px;
        display: flex;

        .label {
          width: 100px;
          color: #909399;
        }

        .description {
          color: #606266;
          line-height: 1.6;
        }
      }
    }
  }
}

.certificate-image {
  width: 60px;
  height: 40px;
  border-radius: 4px;
}

.avatar-uploader,
.certificate-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon,
.certificate-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.certificate {
  width: 148px;
  height: 100px;
  display: block;
}
</style> 